//
//  GeRenSheZhiViewController.m
//  ZhiBoYuan
//
//  Created by coder_di on 2018/4/17.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "GeRenSheZhiViewController.h"
#import "TouXiangTableViewCell.h"
#import "SheZhiTableViewCell.h"
#import "XIUGaiNiChengViewController.h"
//#import "XiuGaiPhoneNumberViewController.h"
#import "XiuGaiMiMaViewController.h"

@interface GeRenSheZhiViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>

@property (nonatomic, strong)UITableView *tableView;

@property(nonatomic,strong) UIImagePickerController *imagePicker; //声明全局的UIImagePickerController

@property (nonatomic, strong)UIImageView *headImageView;

@end

@implementation GeRenSheZhiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人设置";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self addTableView];
    
    [self.tableView registerClass:[TouXiangTableViewCell class] forCellReuseIdentifier:@"TouXiangTableViewCell"];
    [self.tableView registerClass:[SheZhiTableViewCell class] forCellReuseIdentifier:@"SheZhiTableViewCell"];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
    
}

-(void)addTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, Screenheight- NAVIGATION_BAR_HEIGHT) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate        = self;
    _tableView.dataSource      = self;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    _tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    [self.view addSubview:_tableView];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Navigation
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
 -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

 UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth,15)];

 view.backgroundColor = hui1Color;

 return view;

 }

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }else{
        return 15;
    }
   

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 15;
}

#pragma mark -- UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    }else{
        
        return 3;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            static NSString *identifity = @"TouXiangTableViewCell";
            //    MyIndentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifity];
            TouXiangTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            if (cell == nil) {
                cell = [[TouXiangTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifity];
            }
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            cell .accessoryType  = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
            
            _headImageView = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth - 100 * KscreenWidth, 20 * KscreenHeight, 60 * KscreenWidth, 60 * KscreenWidth)];
            _headImageView.layer.masksToBounds = YES;
            //        self.headImageView.userInteractionEnabled = YES;
            _headImageView.contentMode = UIViewContentModeScaleAspectFill;
            _headImageView.clipsToBounds = YES;
            _headImageView.layer.cornerRadius = 30 * KscreenWidth;
            
            NSString *headUrl = [ZYUserManager userInfo].small_img;
            
            [_headImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",headUrl]] placeholderImage:[UIImage imageNamed:@"图层18"]];
            
            [cell.contentView addSubview:_headImageView];
            
            return cell;
        }else{
            static NSString *identifity = @"SheZhiTableViewCell";
            SheZhiTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            if (cell == nil) {
                cell = [[SheZhiTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifity];
            }
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            if (indexPath.row == 1) {
                cell.nameLable.text = @"昵称";
                cell.detailLable.text = [ZYUserManager userInfo].nick_name;
                cell .accessoryType  = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
            }else if (indexPath.row == 2){
                cell.nameLable.text = @"性别";
                
                //添加男女选择
                NSMutableArray* buttons = [NSMutableArray arrayWithCapacity:2];
                CGRect btnRect = CGRectMake(ScreenWidth - 120, 15 * KscreenHeight, 100, 30);
                for (NSString* optionTitle in @[@"男", @"女"]) {
                    RadioButton* btn = [[RadioButton alloc] initWithFrame:btnRect];
                    [btn addTarget:self action:@selector(onRadioButtonValueChanged:) forControlEvents:UIControlEventValueChanged];
                    btnRect.origin.x += 60;
                    [btn setTitle:optionTitle forState:UIControlStateNormal];
                    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
                    btn.titleLabel.font = [UIFont boldSystemFontOfSize:17];
                    [btn setImage:[UIImage imageNamed:@"椭圆1"] forState:UIControlStateNormal];
                    [btn setImage:[UIImage imageNamed:@"椭圆2"] forState:UIControlStateSelected];
                    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
                    btn.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
                    [cell.contentView addSubview:btn];
                    [buttons addObject:btn];
                }
                
                [buttons[0] setGroupButtons:buttons]; // Setting buttons into the group
                
                if ([[ZYUserManager userInfo].sex isEqualToString:@"1"]) {
                    [buttons[0] setSelected:YES];
                }else{
                    [buttons[1] setSelected:YES];
                    
                }
                
            }
           return cell;
        }
        
    }else{
        static NSString *identifity = @"SheZhiTableViewCell";
        SheZhiTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (cell == nil) {
            cell = [[SheZhiTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifity];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        if (indexPath.row == 0) {
            cell.nameLable.text = @"手机号";
            cell.detailLable.text = [ZYUserManager userInfo].phone;
//            cell .accessoryType  = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
        }else if (indexPath.row == 1){
            cell.nameLable.text = @"修改密码";
            cell .accessoryType  = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
            
        }else{
            cell.nameLable.text = @"真实姓名";
            cell.detailLable.text = [ZYUserManager userInfo].name;
        }
        return cell;
        
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0 && indexPath.row == 0) {
        return 100 * KscreenHeight;
    }else{
        
         return 60 * KscreenHeight;
    }
   
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            //头像
            [self takePhotoAction];
            
        }else if (indexPath.row == 1){
            //修改昵称
            XIUGaiNiChengViewController *xiuGaiNiCHengVC = [[XIUGaiNiChengViewController alloc]init];
            [self.navigationController pushViewController:xiuGaiNiCHengVC animated:YES];
            
        }else{
//            性别
            
        }
    }else{
        if (indexPath.row == 0) {
            //修改手机号
//            XiuGaiPhoneNumberViewController *phoneVC = [[XiuGaiPhoneNumberViewController alloc]init];
//            [self.navigationController pushViewController:phoneVC animated:YES];
        }else if (indexPath.row == 1){
            //修改密码
            XiuGaiMiMaViewController *xiugaimimaVC = [[XiuGaiMiMaViewController alloc]init];
            xiugaimimaVC.phoneNumber = @"15811223344";
            [self.navigationController pushViewController:xiugaimimaVC animated:YES];
        }
        
    }
    
}

//选择男女的方法
-(void) onRadioButtonValueChanged:(RadioButton*)sender
{
    int sex = 1;
    
    if(sender.selected) {
                if ([sender.titleLabel.text isEqualToString:@"男"]) {
                    sex = 1;
                }
                if ([sender.titleLabel.text isEqualToString:@"女"]) {
                    sex = 2;
                }
        
        
        SGParameter *parameter  = [[SGParameter alloc] init];
        parameter.body = @{@"sex":[NSString stringWithFormat:@"%d",sex]
                           };
        
        [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=Ucenter&a=changeSex",HTTPP] parameter:parameter sucess:^(id responseObject) {
            NSLog(@"%@",responseObject);
            if ([responseObject[@"status"] intValue] == 200) {
                [MBProgressHUD showTextOnly:self.view message:@"修改成功" delay:2.0];
                
                UserinfoModel *model = [ZYUserManager userInfo];
                model.sex = [NSString stringWithFormat:@"%d",sex];
                
                [ZYUserManager saveUserInfo:model];
                                
            }else{
                
                [MBProgressHUD showTextOnly:self.view message:responseObject[@"msg"] delay:2.0];
            }
            
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            
        }];
        
        

    }
}

//设置头像
- (void)takePhotoAction {
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"拍照",@"从手机相册选择",nil];
    sheet.tag = 2550;
    //    [sheet addButtonWithTitle:@""];
    [sheet showInView:self.view];
}

#pragma mark -消息框代理实现-
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (actionSheet.tag == 2550) {
        NSUInteger sourceType = 0;
        // 判断系统是否支持相机
        _imagePicker = [[UIImagePickerController alloc] init];
            _imagePicker.delegate = self; //设置代理
            _imagePicker.allowsEditing = YES;
            _imagePicker.sourceType = sourceType; //图片来源
            if (buttonIndex == 2) {
                return;
            }else if (buttonIndex == 0) {
                //拍照
                sourceType = UIImagePickerControllerSourceTypeCamera;
                _imagePicker.sourceType = sourceType;
                [self presentViewController:_imagePicker animated:YES completion:nil];
            }else if (buttonIndex == 1){
                //相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                _imagePicker.sourceType = sourceType;
                [self presentViewController:_imagePicker animated:YES completion:nil];
            }
      
    }
}

#pragma mark -----------实现图片选择器代理--------（上传图片的网络请求也是在这个方法里面进行）
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; //通过key值获取到图片
//    _headImageView.image = image;  //给UIimageView赋值已经选择的相片
    
    //上传图片到服务器--在这里进行图片上传的网络请求
    
    [self upDateHeadIcon:image];
    

    
}

- (void)upDateHeadIcon:(UIImage *)photo{
    /*使用Base64字符串传图片*/
    //图片上传
    NSData *data =  UIImageJPEGRepresentation(photo, 0.5);
    NSString * imageStr = [data base64Encoding];
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{@"avatar":imageStr};
    NNSLog(@"=========================================%@",imageStr);
    [MBProgressHUD showLoadingImageToView:self.view];
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=Ucenter&a=uploadAvatarForWeb",HTTPP] parameter:parameter sucess:^(id responseObject) {
        NSLog(@"%@",responseObject);
        
         [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        NSDictionary *dic = responseObject;

        if ([dic[@"status"] intValue] == 200) {
            [MBProgressHUD showTextOnly:self.view message:@"上传成功" delay:3.0f];

            
            UserinfoModel *model = [ZYUserManager userInfo];
            
            
            model.small_img = [dic[@"data"][@"user_info"] valueForKey:@"small_img"];
            model.middle_img = [dic[@"data"][@"user_info"] valueForKey:@"middle_img"];
            model.big_img = [dic[@"data"][@"user_info"] valueForKey:@"big_img"];
            [ZYUserManager saveUserInfo:model];
            [self.tableView reloadData];
            
        }else{
            [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:3.0f];
        }


    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];

    }];

    
}


//当用户取消选择的时候，调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

@end
